package com.amumu.drama.portal.component;

import com.amumu.drama.model.UmsMember;
import com.amumu.drama.portal.config.JWTProperties;
import com.amumu.drama.common.modules.member.service.UmsMemberService;
import com.amumu.drama.security.util.JwtTokenUtil;
import io.micrometer.core.instrument.util.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.core.MethodParameter;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

@Component
@EnableConfigurationProperties(JWTProperties.class)
public class LoginMemberArgResolver implements HandlerMethodArgumentResolver {
    private static final Logger LOGGER = LoggerFactory.getLogger(LoginMemberArgResolver.class);
    @Autowired
    private JWTProperties jwtProperties;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private UmsMemberService memberService;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().equals(UmsMember.class);
    }

    @Override
    public Object resolveArgument(@NotNull MethodParameter parameter,
                                  ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest,
                                  WebDataBinderFactory binderFactory) {
        String authHeader = webRequest.getHeader(jwtProperties.getTokenHeader());
        if (StringUtils.isBlank(authHeader) || !authHeader.startsWith(jwtProperties.getTokenHead())) {
            return null;
        }
        String authToken = authHeader.substring(jwtProperties.getTokenHead().length());// The part after "Bearer "
        String username = jwtTokenUtil.getUserNameFromToken(authToken);
        LOGGER.info("checking username:{}", username);
        if (StringUtils.isBlank(username) || SecurityContextHolder.getContext().getAuthentication() == null) {
            return null;
        }
        return memberService.getByUsername(username);
    }
}
